Delegate is a reference type variable that can hold the reference of a function. It is like a pointer to a method, in C++ or C. Delegates are implicitly driven from the System.Delegate
Class. We can say that it is an object, or reference type variable, which refers to a function, and can hold the reference of a method. Delegates are used to implement events or callback functions.
Delegate Syntax in C#
<<Access_Specifier>> delegate <<Return Type>> <<Delegate_Name>>(Parameters)
Declaration of Delegate in C#
Public delegate int Prime_Delogate(int number);
Why we use Delegate?
A method may have more than one parameter of a different data type. If you want to pass a method into the function’s parameters, then you can use delegates. You can also use delegates to handle the event handler and callback function.
Using delegates, a programmer can encapsulate the reference to the function into a delegate object. Keep in mind that the function’s return type and data type always must match with the delegate’s return type and data type.
Example of Delegate in C#
Here is the simple example of delegates in C#. The code below successfully compiles, and the output is also given below.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication14 { class Program { public delegate void display(int value); public delegate void show(String name); static void Main(string[] args) { display del_Display = Methodshow; del_Display(2000); del_Display(-9000); show del_show = Name; del_show("Delegate Show"); del_show("Introdunction to delegate in C#"); Console.ReadLine(); } public static void Mwthodshow(int val) { Console.WriteLine("Value is : {0}", val); } public static void Name(string name) { Console.WriteLine("Name is : {0}", name); } } }
Program Explanation
In the above program, we have declared two delegates of type void
. The delegates have one parameter of type int
and char
, respectively. In the main function, we have declared the delegate variable of type display and assigned the Methodshow
function name.
We are now calling the del_display
delegate, which will result in a call of the Methodshow
function. Similarly, declaring the show variable and assigned the name function. Now, invoking the del_show
delegate which will result in the call of the name function and result will be printed on the console.
Comments